﻿using System;
using System.Collections.Generic;
using System.Linq;
using Calimbra.Runtime.Contracts;
using Calimbra.Runtime.Data;

namespace Calimbra.Runtime.Functions
{
    public class Map_message_to_input_ports
    {
        private IEnumerable<IStream> streams;

        public void Process(IMessage outputMessage)
        {
            var inputPorts = streams.Where(i => i.FromPort.Name == outputMessage.Port.Name).Select(i => i.ToPort);
            if (inputPorts.Count() == 0)
                throw new InvalidOperationException(string.Format("Unknown output port: '{0}'!", outputMessage.Port.Name));

            foreach (IPort inputPort in inputPorts)
                Result(new Message(inputPort, outputMessage.Data));
        }

        public event Action<IMessage> Result;

        public void Inject(IEnumerable<IStream> streams)
        {
            this.streams = streams;
        }
    }
}